package com.ysm.freestyle.activity

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.FileUtils
import android.os.SystemClock
import android.provider.DocumentsContract
import android.provider.Settings
import android.view.View
import androidx.activity.viewModels
import androidx.annotation.RequiresApi
import androidx.documentfile.provider.DocumentFile
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.TimeUtils
import com.ysm.freestyle.R
import com.ysm.freestyle.base.BaseActivity
import com.ysm.freestyle.utils.FileScanUtils
import com.ysm.freestyle.utils.PermissionUtils.allFilePermission
import com.ysm.freestyle.utils.PermissionUtils.checkPermissions
import com.ysm.freestyle.utils.PermissionUtils.fileRWPermission
import com.ysm.freestyle.utils.PermissionUtils.requestPermission
import com.ysm.freestyle.utils.SCAN_TYPE_DEEP
import com.ysm.freestyle.utils.ScanFileNewUtil
import com.ysm.freestyle.utils.ToastUtil
import com.ysm.freestyle.view.dialog.BottomTransferDialog
import com.ysm.freestyle.view.item.TransferItemView
import com.ysm.freestyle.viewmodel.FileScanViewModel
import com.ysm.freestyle.viewmodel.PathTextViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

class ChatsGoActivity : BaseActivity() {


    private val transferDialog : BottomTransferDialog by lazy {

        BottomTransferDialog(context = this)
            .setDialogTitle(getString(R.string.select_a_transfer_direction))
            .setCloseOnClick { transferDialog.dismiss() }
            .addItemAndOnClick(
                TransferItemView(this).initRes(
                    R.mipmap.icon_basic_data,
                    getString(R.string.basic_data),
                    getString(R.string.desc_transfer_type_desc))
            ) {
                checkAndGoBasicScan()
            }
            .addItemAndOnClick(
                TransferItemView(this).initRes(
                    R.mipmap.icon_other_data,
                    getString(R.string.other_data),
                    getString(R.string.desc_transfer_call_logs))
            ) {
                checkAndGoOtherScan()
            }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_chats_go)
    }




    private fun checkAndGoBasicScan(){
//        ToastUtil.showShortToast(this,"checkAndGoBasicScan！！")

        if (!FileScanUtils.isGrantAndroidDataDirPermission()) {
            //获取data目录访问权限
            val uri =
                Uri.parse(
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                        "content://com.android.externalstorage.documents/tree/primary%3AA%E2%80%8Bndroid%2Fdata"
                    } else{
                        "content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fdata"
                    }
                )
            val documentFile =
                DocumentFile.fromTreeUri(this, uri)
            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
            intent.flags = (Intent.FLAG_GRANT_READ_URI_PERMISSION
                    or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                    or Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
                    or Intent.FLAG_GRANT_PREFIX_URI_PERMISSION)
            documentFile?.let {
                intent.putExtra(
                    DocumentsContract.EXTRA_INITIAL_URI,
                    documentFile.uri
                )
                startActivityForResult(intent, 9969)
            } ?: let {
                ToastUtil.showShortToast (this,"Permission denied. Unable to use the feature.")
            }
        } else {
            startActivity(Intent(this,ScanResultActivity::class.java))
        }
    }



    private fun checkAndGoOtherScan(){
        ToastUtil.showShortToast(this,"checkAndGoOtherScan！！")
    }

    private fun requestAllFilePermission(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
            if(!checkPermissions(this, permissions = allFilePermission)){
                val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:$packageName"));
                startActivity(intent)
            }else{
                requestSuccess()
            }
        }else{
            if(!checkPermissions(this, permissions = fileRWPermission)){
                requestPermission(this, permissions = fileRWPermission,
                    requestSuccess = ::requestSuccess,
                    requestFail = ::requestFail)
            }
        }
    }

    private fun requestSuccess(){
//        ToastUtil.showShortToast(this,"全部授权成功！！")
        transferDialog.show()
    }

    private fun requestFail(context:Context, permissions: MutableList<String>){
        requestPermission(this, permissions = fileRWPermission,
            requestSuccess = ::requestSuccess,
            requestFail = ::requestFail)
    }


    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 9969) {//data文件夹权限获取结果返回
            var uri: Uri? = data?.data
            uri?.let {
                if (data?.flags != null) {//获取成功
                    //保存data权限的获取状态
                    contentResolver.takePersistableUriPermission(
                        it,
                        Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                    )
                    //跳转扫描
                } else {//获取失败
                    ToastUtil.showShortToast(this,"Permission denied. Unable to use the feature.")
                }
            } ?: let {//获取失败
                ToastUtil.showShortToast(this,"Permission denied. Unable to use the feature.")
            }
        }
    }


    fun onPhoneToPhone(view: View) {
        requestAllFilePermission()
    }


    fun onFileTransfer(view: View) {

    }





}